package com.glory.hikvisionmobile.activity;


import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.adapter.DataCollectListAdapter;
import com.glory.hikvisionmobile.base.App;
import com.glory.hikvisionmobile.base.BaseActivity;
import com.glory.hikvisionmobile.base.Constant;
import com.glory.hikvisionmobile.bean.DataCollect.DataCollectBean;
import com.glory.hikvisionmobile.bean.DataCollect.XEdcItemSetLinesBean;
import com.glory.hikvisionmobile.bean.DataCollect.XPdaComponentBean;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.utils.DialogUtils;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class Work_SPCDataCollectActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener {


    @BindView(R.id.tvMainWork)
    TextView tvMainWork;
    @BindView(R.id.tvItemWork)
    TextView tvItemWork;
    @BindView(R.id.tvLotNum)
    TextView tvLotNum;
    @BindView(R.id.tvParamList)
    TextView tvParamList;
    @BindView(R.id.rvDataCollectInfoList)
    RecyclerView rvDataCollectInfoList;
    @BindView(R.id.bottom_tv1)
    TextView bottomTv1;
    @BindView(R.id.bottom_tv2)
    TextView bottomTv2;
    @BindView(R.id.bottom_tv3)
    TextView bottomTv3;
    @BindView(R.id.bottom_tv4)
    TextView bottomTv4;
    @BindView(R.id.bottom_btn_layout)
    LinearLayout bottomBtnLayout;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvPartName)
    TextView tvPartName;
    @BindView(R.id.tvPartDesc)
    TextView tvPartDesc;
    private DataCollectListAdapter dataCollectListAdapter;
    private String lot;
    private String paramsName;
    private String mainDevice;
    private String itemDevice;
    private List<XEdcItemSetLinesBean> xEdcItemSetLinesBeans;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_data_collect;
    }

    @Override
    protected void initView() {
        initBottom();
        Bundle bundle = getIntent().getExtras();
        lot = bundle.getString("lot");
        paramsName = bundle.getString("paramsName");
        mainDevice = bundle.getString("mainDevice");
        itemDevice = bundle.getString("itemDevice");
        tvPartName.setText(bundle.getString("partName"));
        tvPartDesc.setText(bundle.getString("partDesc"));
        tvItemWork.setText(itemDevice);
        tvLotNum.setText(lot);
        tvMainWork.setText(mainDevice);
        tvParamList.setText(paramsName);


        rvDataCollectInfoList.setLayoutManager(new LinearLayoutManager(Work_SPCDataCollectActivity.this));
        rvDataCollectInfoList.setItemAnimator(new DefaultItemAnimator());
        rvDataCollectInfoList.addItemDecoration(new DividerItemDecoration(Work_SPCDataCollectActivity.this, 1));
        dataCollectListAdapter = new DataCollectListAdapter(null);
        dataCollectListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        dataCollectListAdapter.isFirstOnly(true);
        rvDataCollectInfoList.setAdapter(dataCollectListAdapter);
        dataCollectListAdapter.setOnItemClickListener(this);

    }

    private void initBottom() {
        bottomTv1.setText("临时保存");
        bottomTv2.setText("提交");
        bottomTv3.setVisibility(View.GONE);
        bottomTv4.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {

        JsonObject map = new JsonObject();
        map.addProperty("lotId",lot);
        map.addProperty("edcSetId",paramsName);
        map.addProperty("mainEquipmentId",mainDevice);
        NetUtils.requestDara("HIK.PdaOnLineLoad",this,map, new FreeUI_DialogEntityCallBack<BaseResponseBean<DataCollectBean>>
                (new TypeToken<BaseResponseBean<DataCollectBean>>(){}.getType(),getSupportFragmentManager(),this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<DataCollectBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    xEdcItemSetLinesBeans = response.body().getBody().getxEdcItemSetLines();
                    dataCollectListAdapter.setNewData(xEdcItemSetLinesBeans);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<DataCollectBean>> response) {
                super.onError(response);
                loadError(response.getException(),"HIK.PdaOnLineLoad");
            }
        });
    }


    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("数据采集");
        freeUI_titleView.setRightListener(R.drawable.selector_refresh, v -> {
            initPermission("Refresh", this, new ActionControlListener() {
                @Override
                public void onControlChangeListener() {
                    initData();
                }
            });

        });
        return new FreeUI_AddViewEntity("header", llMain);
    }


    @OnClick({R.id.bottom_tv1, R.id.bottom_tv2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bottom_tv1:
                initPermission("TemporarySave", this, new ActionControlListener() {
                    @Override
                    public void onControlChangeListener() {
                        DialogUtils.showLoginDialog(Work_SPCDataCollectActivity.this, Constant.CURRENT_USER, () -> submit("SAVETEMP"),getSupportFragmentManager());
                    }
                });

                break;
            case R.id.bottom_tv2:
                initPermission("Submit", this, new ActionControlListener() {
                    @Override
                    public void onControlChangeListener() {
                        DialogUtils.showLoginDialog(Work_SPCDataCollectActivity.this, Constant.CURRENT_USER, () -> submit("SAVEDONE"),getSupportFragmentManager());
                    }
                });
                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

        if(xEdcItemSetLinesBeans.get(position).getEdcSampleType().equals("ITEM")) {

            Intent intent = new Intent(this,DataCollectDetailsActivity.class);
            intent.putExtra("postion",position);
            intent.putParcelableArrayListExtra("xEdcItemSetLinesBeans", (ArrayList<? extends Parcelable>) xEdcItemSetLinesBeans);
            startActivityForResult(intent,100);

        }else if(xEdcItemSetLinesBeans.get(position).getEdcSampleType().equals("COMP")||xEdcItemSetLinesBeans.get(position).getEdcSampleType().equals("SITE")){

            if(xEdcItemSetLinesBeans.get(position).getXPdaDcModels().size()>0) {
                FreeApi_DialogUtils.getConfirmAndCancelDialog(Work_SPCDataCollectActivity.this, "确定", "取消", "当前已有数据，是否重新选择片号", () -> {
                    DialogUtils.showWaferDialog(this, xEdcItemSetLinesBeans.get(position).getxPdaComponents(), (isChange) -> {

                        if (isChange)
                            xEdcItemSetLinesBeans.get(position).getXPdaDcModels().clear();
                        Intent intent = new Intent(this, DataCollectDetailsActivity.class);
                        intent.putExtra("postion", position);
                        intent.putParcelableArrayListExtra("xEdcItemSetLinesBeans", (ArrayList<? extends Parcelable>) xEdcItemSetLinesBeans);
                        startActivityForResult(intent, 100);

                    }, getSupportFragmentManager());
                }, () -> {
                    Intent intent = new Intent(this, DataCollectDetailsActivity.class);
                    intent.putExtra("postion", position);
                    intent.putParcelableArrayListExtra("xEdcItemSetLinesBeans", (ArrayList<? extends Parcelable>) xEdcItemSetLinesBeans);
                    startActivityForResult(intent, 100);
                }).show(getSupportFragmentManager(),"SPC_TAG");
            }else{
                DialogUtils.showWaferDialog(this, xEdcItemSetLinesBeans.get(position).getxPdaComponents(), (isChange) -> {

                    if (isChange)
                        xEdcItemSetLinesBeans.get(position).getXPdaDcModels().clear();
                    Intent intent = new Intent(this, DataCollectDetailsActivity.class);
                    intent.putExtra("postion", position);
                    intent.putParcelableArrayListExtra("xEdcItemSetLinesBeans", (ArrayList<? extends Parcelable>) xEdcItemSetLinesBeans);
                    startActivityForResult(intent, 100);

                }, getSupportFragmentManager());
            }
        }
    }

    private void submit(String action)
    {
        JsonObject map = new JsonObject();
        map.addProperty("edcSetId",paramsName);
        map.addProperty("mainEquipmentId",mainDevice);
        map.addProperty("lotId",lot);
        map.addProperty("actionType",action);
        JsonArray jsonArray = new JsonArray();

        for (XEdcItemSetLinesBean xEdcItemSetLinesBean : xEdcItemSetLinesBeans) {
            JsonObject js = new JsonObject();
            JsonObject js1 = new JsonObject();
            js1.add("XPdaDcModel",new JsonParser().parse(new Gson().toJson(xEdcItemSetLinesBean.getXPdaDcModels())).getAsJsonArray());
            js.add("XPdaDcModels",js1);
            JsonObject js2 = new JsonObject();
            js2.add("XPdaComponent",new JsonParser().parse(new Gson().toJson(xEdcItemSetLinesBean.getxPdaComponents())).getAsJsonArray());
            js.add("xPdaComponents",js2);
            js.addProperty("edcItemLineName",xEdcItemSetLinesBean.getEdcItemLineName());
            js.addProperty("dataType",xEdcItemSetLinesBean.getDataType());
            js.addProperty("edcSampleType",xEdcItemSetLinesBean.getEdcSampleType());
            jsonArray.add(js);
        }
        JsonObject js3 = new JsonObject();
        js3.add("XPdaEdcData",new JsonParser().parse(new Gson().toJson(jsonArray)));
        map.add("xPdaEdcDatas",js3);
        NetUtils.requestDara("HIK.PdaOnLineSubmit",this,map, new FreeUI_DialogEntityCallBack<BaseResponseBean<?>>
                (new TypeToken<BaseResponseBean<?>>(){}.getType(),getSupportFragmentManager(),this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<?>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    if (action.equals("SAVEDONE")){
                        showToast("提交成功",true);
                        finish();
                        return;
                    }else {
                        for (XEdcItemSetLinesBean bean : xEdcItemSetLinesBeans){
                            for (XPdaComponentBean component : bean.getxPdaComponents()){
                                component.setIsSelected("");
                            }
                        }
                        showToast("临时保存成功",true);
                    }


                }
            }

            @Override
            public void onError(Response<BaseResponseBean<?>> response) {
                super.onError(response);
                loadError(response.getException(),"HIK.PdaOnLineSubmit");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK){
            if (requestCode == 100){
                if (data != null){
                    xEdcItemSetLinesBeans = data.getParcelableArrayListExtra("xEdcItemSetLinesBeans");
                }
            }
        }

    }
}
